import storage from 'src/utils/storage';
import API from './repository/dictionaries';

/**
 * 商机状态
 * @type {*[]}
 */
const OpportunityStates = [
    {
        text: '未激活',
        value: 'INIT',
    },
    {
        text: '有意向',
        value: 'CHANCE',
    },
    {
        text: '已联系',
        value: 'CONTACTED',
    },
    {
        text: '已试用',
        value: 'TRIAL',
    },
    {
        text: '已成交',
        value: 'DEAL',
    },
    {
        text: '废弃',
        value: 'TRASH',
    }
];

/**
 * 部门员工类型
 * @type {*[]}
 */
const DepartmentUserTypes = [
    {
        text: '员工',
        value: 'EMPLOYEE'
    },
    {
        text: '管理',
        value: 'MANAGER'
    }
];

/**
 * 商机业务状态
 * @type {{}}
 */
const OpportunityBusinessState = [
    {
        text: '未注册',
        value: 'UNREGISTER'
    },
    {
        text: '信息不完善',
        value: 'HALF'
    },
    {
        text: '已注册',
        value: 'REGISTERED'
    },
    {
        text: '已成交',
        value: 'PAID'
    },
];

/**
 * 替换字典值
 * @param dict
 * @param value
 * @returns {string}
 */
const replaceDictionary = function(value, dict = getDictionary()) {
    let index = dict.findIndex((item) => {
        return item.value === value;
    });
    return index >= 0 ? dict[index].text : '无效字典值';
};

const DictionaryKey = 'dk';

/**
 * 获取字典
 * @returns {*}
 */
const getDictionary = function() {
    return storage.get(DictionaryKey) || [];
};

/**
 * 检查字典是否需要更新
 * @returns {*}
 */
const checkDictionary = function() {
    return getDictionary().length > 0;
};

/**
 * 将从后台传入的字典数据格式化
 * @param res
 */
const formatDictionaryFromAPI = function(res) {
    let origin = res._embedded.dictionaries || [];
    let dictionary =  origin.map(item => {
        return {
            text: item.name,
            value: item.code,
            sort: item.sort,
            type: item.type
        };
    });
    // 排序
    dictionary.sort((a, b) => a.sort - b.sort);
    return dictionary;
};

/**
 * 更新本地字典
 */
const updateDictionary = function() {
    return new Promise((resolve, reject) => {
        if (checkDictionary()) {
            resolve(getDictionary());
        } else {
            API.fetchAll()
                .then(res => {
                    let dictionary = formatDictionaryFromAPI(res);
                    storage.set(DictionaryKey, dictionary);
                    resolve(dictionary);
                })
                .catch(err => {
                    reject(err);
                });
        }
    });
};

/**
 * 清理字典
 */
const clearDictionaryCache = function() {
    storage.remove(DictionaryKey);
};

export default {
    OpportunityStates,
    DepartmentUserTypes,
    OpportunityBusinessState,
    replaceDictionary,
    updateDictionary,
    getDictionary,
    checkDictionary,
    clearDictionaryCache,
    /**
     * 行业类型
     */
    get IndustryType() {
        return getDictionary().filter(item => item.type === 'INDUSTRY');
    }
};